//
//  USEaseIMHelper.m
//  us
//
//  Created by karry on 2025/4/15.
//

#import "USEaseIMHelper.h"

#import "USEMRemindManager.h"
#import "USInAppNotificationBanner.h"
#import "USChatController.h"
#import "MatchViewController.h"
#import "USAskDetailViewController.h"
#import "USTodayTarotController.h"
#import "USTarotCardDetailController.h"
#import "USMemorialDayDetailVC.h"
#import "USMomentsDetailController.h"
#import "USAddOurListSubListController.h"
#import "USAlbumPhotoListController.h"
#import "USLoveCompassViewController.h"
#import "USLoveCompassGuideController.h"
#import "USTarotCard.h"
#import "SceneDelegate.h"
#import "USRealtimeLocationManager.h"
static USEaseIMHelper *helper = nil;


@implementation USEaseIMHelper

+ (instancetype)shareHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[USEaseIMHelper alloc] init];
    });
    return helper;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self _initHelper];
    }
    return self;
}

- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[EMClient sharedClient].contactManager removeDelegate:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - init

- (void)_initHelper
{
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient] addMultiDevicesDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    
}
#pragma mark - EMChatManagerDelegate

/// 这里处理需要弹窗的CMD
- (void)cmdMessagesDidReceive:(NSArray<EMChatMessage *> *)aCmdMessages {
    

    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateBackground) {
        return;
    }
    
    EMChatMessage *msg = aCmdMessages.firstObject;

    if ([msg.body isKindOfClass:[EMCmdMessageBody class]] && msg.direction == EMMessageDirectionReceive) {
        EMCmdMessageBody *body = (EMCmdMessageBody *)msg.body;
        NSString *action = body.action;
        
        NSLog(@"1111111 📩 收到CMD消息：%@ from: %@", action, msg.from);
   
        
        BOOL needShowBanner = NO;
        NSString *action_id = @"";
        NSString *title = @"";
        NSString *content = @"";

        NSLog(@"ext  =  %@",msg.ext);
        NSDictionary *customExt = msg.ext;
        if ([customExt.allKeys containsObject:@"action_title"]) {
            //显示的文本内容
            title = customExt[@"action_title"];
            needShowBanner = YES;
        }
        if ([customExt.allKeys containsObject:@"action_content"]) {
            //显示的文本内容
            content = customExt[@"action_content"];
            needShowBanner = YES;
        }
        if ([customExt.allKeys containsObject:@"action_id"]) {
            //需要跳转的id，比如问答id
            action_id = customExt[@"action_id"];
         }
        if (needShowBanner) {
            [[USInAppNotificationBanner sharedBanner] showWithAvatar:NO
                                                               title:title
                                                             message:content
                                                          tapHandler:^{
                
                [self jumpWithActionType:action andActionId:action_id];
       
            }];
        }
        
  
    }
  
}
 
- (void)jumpWithActionType:(NSString *)actionType andActionId:(NSString *)actionId {
    
    if ([actionType isEqualToString:USIMCmdAction_TalkNotic]) {
        //1、问答
        USAskDetailViewController *vc = [USAskDetailViewController new];
        vc.dailyTalkId = actionId;
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
    }else if ([actionType isEqualToString:USIMCmdAction_TarotNotic]) {
        //2、塔罗牌
        [self getTodayTarot];
    }else if ([actionType isEqualToString:USIMCmdAction_ListDone]) {
        //3、清单
        USAddOurListSubListController *vc = [USAddOurListSubListController new];
        vc.sweetChallengeId = actionId;
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
    }else if ([actionType isEqualToString:USIMCmdAction_PushMoment]) {
        //4、日记
        USMomentsDetailController *vc = [USMomentsDetailController new];
        vc.moodDiaryId = actionId;
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
    }else if ([actionType isEqualToString:USIMCmdAction_MemorialDay]) {
        //5、纪念日
        USMemorialDayDetailVC *vc = [USMemorialDayDetailVC new];
        vc.anniversaryId = actionId;
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
    }else if ([actionType isEqualToString:USIMCmdAction_Photo]) {
        //6、相册
        USAlbumPhotoListController *vc = [USAlbumPhotoListController new];
        vc.albumId = actionId;
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
    }else if ([actionType isEqualToString:USIMCmdAction_Location]) {
        //7、位置
        [self compassAction:nil];
    }

}

//获取今日塔罗牌状态
- (void)getTodayTarot{
     [[EMNetWork shareManager] em_post:TarotToday
                               params:nil
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
        if (!api.success) {
            return;
        }
        USTarotModel *tarotModel = [USTarotModel mj_objectWithKeyValues:api.data[@"totalTarot"]];

        if (tarotModel.myStatus == 1 && tarotModel.tarotDetailList.count > 0) {
            USTarotCardDetailController *vc = [[USTarotCardDetailController alloc]init];
            if (tarotModel) {
                vc.tarotModel = tarotModel;
                
                for (USTarotDetailModel *detailModel in tarotModel.tarotDetailList) {
                    USTarotCard *card = [USTarotCard new];
                    
                    card = [[USTarotCard alloc] init];
                    card.name = detailModel.tarotTitle;
                    card.orientation = detailModel.orientation;
                    card.imageName = detailModel.tarotTitle;
                    card.answer = detailModel.tarotContent;
                    card.date = [NSDate dateWithTimeIntervalSince1970:detailModel.gmtCreate];
                    if ([detailModel.userId isEqualToString:USUser.user.userId]) {
                        vc.activeCard = card;
                    }else {
                        vc.relActiveCard = card;
                    }
                }
               
            }
            [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
            
        }else {
            USTodayTarotController *vc = [USTodayTarotController new];
            vc.tarotModel = tarotModel;
            [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
            
        }
    } fail:^{
        
 
    }];
}
- (void)compassAction:(id)sender{
 
    if ([[NSUserDefaults standardUserDefaults]boolForKey:USKeyHaveOpenLoveCompass] == YES) {
        
        USLoveCompassViewController *vc = [USLoveCompassViewController new];
        [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    
    USLoveCompassGuideController *vc = [USLoveCompassGuideController new];
    @weakify(self)
    vc.didStartBlock = ^{
        @strongify(self)
        [UIViewController.topViewController.navigationController popViewControllerAnimated:YES];
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:USKeyHaveOpenLoveCompass];
        [self updateLocationIfNeed];
        [self compassAction:nil];
    };
    [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
    
}


///当用户开启指南针功能，并且有匹配用户开启
- (void)updateLocationIfNeed{
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:USKeyHaveOpenLoveCompass]) {
        return;
    }
    
    if (USUser.user.relType != 1) {
        return;
    }
    
    //十分钟传一次
    [[USRealtimeLocationManager shared]startDispatchingWithInterval:60 * 10];
    
}


#pragma mark - EMChatManagerDelegate

- (void)messagesDidReceive:(NSArray *)aMessages{
  
    EMChatMessage *msg = aMessages.firstObject;
    [USEMRemindManager remindMessage:msg];
    
    
    BOOL isBackground = NO;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateBackground) {
        isBackground = YES;
    }
    
    if (![UIViewController.topViewController isKindOfClass:NSClassFromString(@"USChatController")] && !isBackground){
        [self showNotificationWithMessage:msg];
    }
    
    for (EMChatMessage *message in aMessages) {
        
        NSLog(@"message.body  =  %@",message.ext);
        if ([message.ext.allKeys containsObject:@"us_system"]) {
            if ([message.ext[@"us_system"] boolValue]  == YES) {
                //系统消息不显示并且删除
                
                
                EMConversation *conversation = [EMClient.sharedClient.chatManager getConversation:USUser.user.relImUserName type:EMConversationTypeChat createIfNotExist:YES];
                
                [conversation deleteMessageWithId:message.messageId error:nil];
//                [conversation removeMessagesFromServerMessageIds:@[message.messageId] completion:^(EMError * _Nullable aError) {
//                    if (aError) {
//                        NSLog(@"删除失败 -- %@",aError.errorDescription);
//                    }
//                }];
            }
        }
     }

    UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
    
    SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
    // 获取指定会话 ID 的会话。
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:USUser.user.relImUserName type:EMConversationTypeChat createIfNotExist:YES];
    // 获取未读消息数。
    NSInteger unreadCount = conversation.unreadMessagesCount;
    [sceneDelegate updateChatBadge:unreadCount];
    
}


- (NSString *)formattedDurationStringFromInt:(int)duration {
    int minutes = duration / 60;
    int seconds = duration % 60;
    
    if (minutes > 0) {
        return [NSString stringWithFormat:@"%d’%d”", minutes, seconds];
    } else {
        return [NSString stringWithFormat:@"%d”", seconds];
    }
    
}
- (void)showNotificationWithMessage:(EMChatMessage *)message {
    
    NSString *msg = @"";
    if (message.body.type == EMMessageBodyTypeText) {
        EMTextMessageBody *body = (EMTextMessageBody *)message.body;
        msg = body.text;
    }else if (message.body.type == EMMessageBodyTypeImage){
        msg = @"[图片]";
    }else if (message.body.type == EMMessageBodyTypeVoice){
        EMVoiceMessageBody *body = (EMVoiceMessageBody *)message.body;
        msg = [NSString stringWithFormat:@"[语音] %@",[self formattedDurationStringFromInt:body.duration]];
    }else if (message.body.type == EMMessageBodyTypeCustom){
        EMCustomMessageBody *body = (EMCustomMessageBody *)message.body;
        if ([body.event isEqualToString:@"emoji"]) {
            msg = @"[动画表情]";
        }else if ([body.event isEqualToString:@"realtime_location"]){
            return;
        }else{
            //其他自定义消息不做弹窗处理，透传处理
            return;
        }
    }
    NSString *title = USUser.user.relUser.nickname;
    [[USInAppNotificationBanner sharedBanner] showWithAvatar:YES
                                                       title:title
                                                     message:msg
                                                  tapHandler:^{
        // 跳转到消息页面
        if (USUser.user.relStatus == 1) {
            USChatController *vc = [USChatController new];
            vc.conversationId = USUser.user.relImUserName;
            [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
            
        }else {
            MatchViewController *vc = [[MatchViewController alloc]init];
            [UIViewController.topViewController.navigationController pushViewController:vc animated:YES];
        }
    }];
    
}


#pragma mark - private

- (BOOL)_needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EMClient sharedClient].groupManager getGroupsWithoutPushNotification:nil];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    return ret;
}


@end
